﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
using CommonLib;

namespace NetService
{
    public static class PageService
    {
        public static string GetPage(string url, Encoding encoding = null)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
            request.Credentials = CredentialCache.DefaultCredentials;

            WebResponse response = null;
            try
            {
                response = request.GetResponse();
            }
            catch (WebException)
            {
                return string.Empty;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message + "\n\nUrl: " + url);
            }


            // Get the stream associated with the response.
            var receiveStream = response.GetResponseStream();

            if(encoding == null)
                encoding = Encoding.Default;

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            var readStream = new StreamReader(receiveStream, Encoding.UTF8);

            return readStream.ReadToEnd();
        }
    }
}
